<script setup lang="ts">
import { ref, onMounted } from 'vue'
import {
  getTrademarkAPI,
  addTrademarkAPI,
  editTrademarkAPI,
  getTrademarkItemAPI,
  removeTrademarkItemAPI,
} from '@api/product/trademark/index.ts'
import type { trademarkListType, listType } from '@api/product/trademark/type'
import { ElMessage } from 'element-plus'

// 表格模块---------------------------------------
const tableData = ref<listType[]>([])
const pageSize = ref<number>(10)
const currentPage = ref<number>(1)
const total = ref<number>(0)
const loading = ref(false)

// 切换每页条数
const handleSizeChange = (e: number) => {
  pageSize.value = e
  getTrademarkFn()
}

// 切换第几页
const handleCurrentChange = (e: number) => {
  currentPage.value = e
  getTrademarkFn()
}

// 获取数据
const getTrademarkFn = async () => {
  const res: trademarkListType = await getTrademarkAPI(
    currentPage.value,
    pageSize.value,
  )
  if (res.code === 200) {
    total.value = res.data.total
    tableData.value = res.data.records
    loading.value = false
  }
}

onMounted(() => getTrademarkFn())

// dialog对话框模块---------------------------------------
// 组件显隐与标题
const dialogVisible = ref<boolean>(false)
const dialogTitle = ref<string>('')

// 显示对话框
const handleDialogShowFn = (type: string, id: string = '') => {
  switch (type) {
    case 'add':
      dialogTitle.value = '添加品牌'
      break
    case 'edit':
      dialogTitle.value = '修改品牌'
      form.value.id = parseInt(id)
      getTrademarkItemAPI(id).then((res) => {
        form.value = res.data
      })
      break
    default:
      break
  }
  dialogVisible.value = true
}

// 对话框内容表单
const form = ref<listType>({
  tmName: '',
  logoUrl: '',
})

// 图片上传前的钩子
const beforeUploadFn: any['beforeUpload'] = (rawFile: {
  type: string
  size: number
}) => {
  console.log(rawFile)

  if (
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/gif' &&
    rawFile.type !== 'image/jpg'
  ) {
    ElMessage.error('图片只能是JPG、PNG、GIF格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('图片最大不可超过4MB!')
    return false
  }
  return true
}

// 上传图片成功回调
const handleAvatarSuccess = (e: { data: string }) => {
  form.value.logoUrl = e.data
  // 上传成功后清除图片校验
  ruleFormRef.value.clearValidate()
}

// 表单校验

const rules = ref<any>({
  tmName: [
    { required: true, message: '请输入品牌名称', trigger: ['change', 'blur'] },
    { min: 2, message: '品牌名称最少两位字符', trigger: ['change', 'blur'] },
  ],
  logoUrl: [
    { required: true, message: '请上传品牌LOGO', trigger: ['change', 'blur'] },
  ],
})

// 点击对话框取消按钮
const handleCancelFn = () => {
  dialogVisible.value = false
  form.value = {
    tmName: '',
    logoUrl: '',
  }
  ruleFormRef.value.resetFields()
}

// 点击对话框确认按钮
const ruleFormRef = ref<any>(null)
const handleComfirmFn = (formEl: any) => {
  if (!formEl) return
  formEl.validate(
    async (valid: boolean, fields: { [x: string]: { message: any }[] }) => {
      if (valid) {
        loading.value = true
        if (form.value.id) {
          // 编辑操作
          const res = await editTrademarkAPI(form.value)
          console.log(res)
          if (res.code === 200) {
            ElMessage.success('修改成功')
          }
        } else {
          // 新增操作
          const res = await addTrademarkAPI(form.value)
          console.log(res)
          if (res.code === 200) {
            ElMessage.success('添加成功')
          }
        }
        getTrademarkFn()
        handleCancelFn()
      } else {
        ElMessage.error(fields[Object.keys(fields)[0]][0].message)
      }
    },
  )
}

// 删除事件---------------------
const handleDeleteFn = async (id: string) => {
  loading.value = true
  await removeTrademarkItemAPI(id)
  getTrademarkFn()
}
</script>

<template>
  <div>
    <el-card class="box-card">
      <el-button type="primary" icon="Plus" @click="handleDialogShowFn('add')">
        添加品牌
      </el-button>
      <!-- 表格组件 -->
      <el-table v-loading="loading" border :data="tableData">
        <el-table-column
          type="index"
          prop="index"
          label="序号"
          width="180"
          align="center"
        />
        <el-table-column prop="tmName" label="品牌名称">
          <!-- 默认以div标签渲染。通过插槽实现其他标签渲染 -->
          <template #default="{ row }">
            <pre style="color: cadetblue">{{ row.tmName }}</pre>
          </template>
        </el-table-column>
        <el-table-column prop="logoUrl" label="品牌LOGO">
          <template #default="{ row }">
            <el-image
              style="width: 100%; height: 100%"
              :src="row.logoUrl"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template #default="{ row }">
            <el-button
              type="warning"
              size="small"
              icon="edit"
              @click="handleDialogShowFn('edit', row.id)"
            ></el-button>
            <el-popconfirm title="是否要删除该数据？" @confirm="handleDeleteFn(row.id)">
              <template #reference>
                <el-button type="danger" size="small" icon="delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 50, 100, 200]"
        :small="true"
        :background="true"
        layout="prev, pager, next, jumper, total, sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 对话框组件 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="50%"
      @close="handleCancelFn"
    >
      <el-form
        ref="ruleFormRef"
        :rules="rules"
        :model="form"
        style="width: 80%"
      >
        <el-form-item prop="tmName" label="品牌名称" label-width="105px">
          <el-input v-model="form.tmName" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item prop="logoUrl" label="品牌LOGO" label-width="105px">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :limit="1"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeUploadFn"
          >
            <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancelFn">取消</el-button>
          <el-button type="primary" @click="handleComfirmFn(ruleFormRef)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>

<style lang="scss" scoped>
:deep(.el-table) {
  margin: 20px 0;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
